import mongoose from 'mongoose';
import Router from 'koa-router';
import assert from 'assert';
import moment from 'moment';
import tokenAuth from '../middleware/tokenAuth';
import messageHandler from '../handler/messageHandler';

const router = new Router({
  prefix: '/api/queue',
});

const Queue = mongoose.model('Queue');
const User = mongoose.model('User');

router.use(tokenAuth());

router.post('/', async (ctx) => {
  const { type, page = 1, pageSize = 10 } = ctx.request.body;
  assert(type !== undefined, 'Queue type should exist');

  const skipCount = (page - 1) * pageSize;

  const condition = {
    type,
    resolved: false,
    createdAt: { $gt: moment().subtract(2, 'day').toDate() },
  };
  const count = await Queue.count(condition);
  const result = await Queue.find(condition)
    .skip(skipCount)
    .limit(pageSize);

  ctx.body = {
    ok: true,
    result,
    page,
    pageSize,
    total: count,
  };
});

const BUYING = 1;
const TYPED_MESSAGES = {
  [BUYING]: '家长，你好，我是久趣助教。 \n\n' +
  '为了提供更好的服务，我们不会打电话联系，打扰到家长，通过本微信服务号您可以随时发消息给我们，我们会第一时间解答您的问题。\n\n' +
  '首次上课，请<a href="http://mp.weixin.qq.com/s/MSWyDXWv-d6OcgUZ4yZiJw">点击详情</a>，了解如何上课。',
};
router.post('/notify', async (ctx) => {
  const { notifications } = ctx.request.body;

  assert(notifications && Array.isArray(notifications), 'notifications should exist');

  const records = await Queue.find({ _id: { $in: notifications }, resolved: false });

  const systemRobot = await User.getSystemRobot();
  const resolved = [];
  for (const record of records) {
    const body = TYPED_MESSAGES[record.type];

    assert(body, '发送消息体未定义, 请联系技术人员');
    // eslint-disable-next-line
    await messageHandler.post(record.targetChannel.toString(), systemRobot, {
      toSocialId: record.fromSocialId,
      subType: 'text',
      body,
    });

    record.resolved = true;
    // eslint-disable-next-line
    await record.save();
    resolved.push(record.id);
  }

  ctx.body = {
    ok: true,
    resolved,
  };
});

export default router;
